﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MisClient
{
    public partial class FrmInvoice : BaseForm
    {
        private IBLL.ICustomer cusBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteCustomer();
        private IBLL.ICusDep cusDepBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteCusDep();
        private IBLL.ISacf sacfBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteSacf();

        public FrmInvoice()
        {
            InitializeComponent();
        }

        private void FrmInvoice_Load(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;
            this.openStarDate.Value = dt.Date.AddDays(-111);
            this.txtOperUser.Text = accountUser.UserCode;
            this.txtDate.Text = DateTime.Now.ToShortDateString();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;
            this.openEndDate.Value = dt;
            this.openStarDate.Value = dt.Date.AddDays(-111);
            this.txtCusCode.Clear();
            this.txtCus.Clear();
            this.txtInvoiceNum.Clear();
            this.txtCusDepCode.Clear();
            this.txtCusDep.Clear();
            this.txtInvoiceCode.Clear();
            this.chkF.Clear();

            this.dataGridView1.Rows.Clear();
            this.dataGridView2.Rows.Clear();
            this.chkF.Text = "Y";

            this.openEndDate.Enabled = true;
            this.openStarDate.Enabled = true;
            this.txtCusCode.Enabled = true;
            this.txtInvoiceNum.Enabled = true;
            this.txtCusDepCode.Enabled = true;
            this.txtInvoiceCode.Enabled = true;
            this.chkF.Enabled = true;

            this.txtNo.Clear();
            this.txtSm1.Clear();
            this.txtSm2.Clear();
            this.txtKd.Clear();
            this.txtTh.Clear();
            this.txtKp.Clear();
            this.txtSk.Clear();
            this.txtZw.Clear();
            this.txtBei.Clear();
            this.txtTotalNum.Clear();
            this.txtTotalQuantity.Clear();
            this.txtSumJe.Clear();
            this.txtNoSumJe.Clear();

            this.btnAdd.Enabled = false;
            this.btnPrint.Enabled = false;
            this.btnQuit.Enabled = false;
            this.btnCan.Enabled = true;

            this.openStarDate.Focus();
        }

        private void txtCusCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrEmpty(this.txtCusCode.Text.Trim()))
                {
                    MisModel.Customer customer = cusBLL.GetById(this.txtCusCode.Text.Trim());
                    if (customer == null)
                    {
                        MessageBox.Show("无此代码或不属于本部分！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtCusCode.Focus();
                        return;
                    }
                    else
                    {
                        this.txtCus.Text = customer.Customer_;
                        MisModel.CusDep cusDep = cusDepBLL.GetById(this.txtCusCode.Text.Trim());
                        if(cusDep!=null)
                        {
                            this.txtCusDepCode.Text = cusDep.CusDep_;
                            this.txtCusDep.Text = cusDep.Depart;
                        }
                    }
                }
                this.txtInvoiceNum.Focus();
            }
        }

        private void txtInvoiceNum_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (string.IsNullOrEmpty(this.txtInvoiceNum.Text.Trim()))
                {
                    MessageBox.Show("不能为空！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtInvoiceNum.Focus();
                    return;
                }
                else
                    this.txtCusDepCode.Focus();
            }
        }

        private void txtCusDepCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtInvoiceCode.Focus();
            }
        }

        private void chkF_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrEmpty(this.txtCusCode.Text.Trim()))
                {
                    MisModel.Customer customer = cusBLL.GetById(this.txtCusCode.Text.Trim());
                    if (customer == null)
                    {
                        MessageBox.Show("无此代码或不属于本部分！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtCusCode.Focus();
                        return;
                    }
                }
                if (string.IsNullOrEmpty(this.txtInvoiceNum.Text.Trim()))
                {
                    MessageBox.Show("不能为空！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtInvoiceNum.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(this.chkF.Text.Trim()))
                {
                    MessageBox.Show("不能为空！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.chkF.Focus();
                    return;
                }
                else if (!this.chkF.Text.Trim().ToUpper().Equals("Y") && !this.chkF.Text.Trim().ToUpper().Equals("N"))
                {
                    MessageBox.Show("应置为：Y(是)或N(否)！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.chkF.Focus();
                    return;
                }

                this.openEndDate.Enabled = false;
                this.openStarDate.Enabled = false;
                this.txtCusCode.Enabled = false;
                this.txtInvoiceNum.Enabled = false;
                this.txtCusDepCode.Enabled = false;
                this.txtInvoiceCode.Enabled = false;
                this.chkF.Enabled = false;
                this.chkF.Enabled = false;

                this.txtNo.Enabled = true;
                this.txtNo.Focus();
                this.btnDelRecord.Enabled = true;
                this.btnAddRecord.Enabled = true;
                this.btnSave.Enabled = true;
            }
        }

        private void txtNo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (string.IsNullOrEmpty(this.txtNo.Text.Trim()))
                {
                    MessageBox.Show("请输入欲确认的单据编号！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtNo.Focus();
                    return;
                }
                IList<MisEntity.Sacf> sacfList = sacfBLL.FindAll(this.txtNo.Text.Trim());
                if (sacfList == null || sacfList.Count<=0)
                {
                    MessageBox.Show("无此单据号！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtNo.Focus();
                    return;
                }
                MisEntity.Sacf sacf = sacfList[0];
                if (!string.IsNullOrEmpty(this.txtCusCode.Text.Trim()))
                {
                    if (!this.txtCusCode.Text.Trim().Equals(sacf.CUS_ID.Trim()))
                    {
                        MessageBox.Show(string.Format("此单据客户为{0},不可操作！", sacf.CUS_ID), "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtNo.Focus();
                        return;
                    }
                }
                if (!string.IsNullOrEmpty(sacf.F3.ToString().Trim()))
                {
                    MessageBox.Show(string.Format("此单据已开发票，不可操作！", sacf.CUS_ID), "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtNo.Focus();
                    return;
                }
                string shopCode = sacf.SHOP_ID;
                this.txtSm1.Text = string.Format("{0}-{1}-{2}", sacf.CUS_ID, sacf.CUS_DEP, sacf.CUS_SHOP);
                decimal jeFs = 0;
                decimal jeHs = 0;
                int slP = 0;
                short tax = 0;
                foreach (MisEntity.Sacf L_Sacf in sacfList)
                {
                    jeFs += (decimal)L_Sacf.JE_FS;
                    jeHs += (decimal)L_Sacf.JE_HS;
                    slP += (int)L_Sacf.SL_P;
                    if (tax < L_Sacf.TAX) tax = (short)L_Sacf.TAX;
                }
                this.textBox1.Text =string.Format("{0}",jeFs);
                this.textBox16.Text = string.Format("{0}", tax);
                this.txtSm2.Text = string.Format("库:{0} 未税额:{1} 含税额:{2} 件数:{3} 税率:{4}", shopCode, jeFs, jeHs, slP, tax);
                this.txtKd.Text = string.Format("{0:f}", sacf.DATE);
                this.txtTh.Text = string.Format("{0:f}", sacf.D_TH);
                this.txtKp.Text = string.Format("{0:f}", sacf.D_KP);
                this.txtSk.Text = string.Format("{0:f}", sacf.D_JS);
                this.txtZw.Text = "Y";
                this.txtTotalNum.Text = "0";
                this.txtTotalQuantity.Text = "0";

                this.txtBei.Enabled = true;
                this.textBox15.Enabled = true;
                this.textBox16.Enabled = true;
                this.textBox17.Enabled = true;

                this.txtBei.Focus(); 
            }
        }

        private void btnAddRecord_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtNo.Text.Trim()))
            {
                MessageBox.Show("请输入合法的单据号！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtNo.Focus();
                return;
            }
            if (string.IsNullOrEmpty(this.txtSm1.Text.Trim()))
            {
                MessageBox.Show("请先确认单据号！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtNo.Focus();
                return;
            }
            IList<MisEntity.Sacf> sacfList = sacfBLL.FindAll(this.txtNo.Text.Trim());
            if (sacfList == null || sacfList.Count <= 0)
            {
                MessageBox.Show("无此单据号，请先设置！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtNo.Focus();
                return;
            }
            String no = this.txtNo.Text.Trim();
            int rowCount = this.dataGridView1.RowCount;
            if (rowCount > 0)
            {
                DataGridViewRow dr = null;
                for (int i = 0; i < rowCount; i++)
                {
                    dr = this.dataGridView1.Rows[i];
                    if (no.Equals(dr.Cells["invoice"].Value.ToString()))
                    {
                        MessageBox.Show("单据不可重复！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtNo.Focus();
                        return;
                    }
                }
            }
            decimal jeFs = 0;
            decimal jeHs = 0;
            foreach (MisEntity.Sacf L_Sacf in sacfList)
            {
                jeFs += (decimal)L_Sacf.JE_FS;
                jeHs += (decimal)L_Sacf.JE_HS;
            }
            String txtZw = this.txtZw.Text.Trim();
            if (!txtZw.ToUpper().Equals("Y"))
                txtZw = "N";
            String[] DataRow = new String[8];
            DataRow[0] = (rowCount + 1).ToString();
            DataRow[1] = no;
            DataRow[2] = txtZw;
            DataRow[3] = this.txtKd.Text.Trim();
            DataRow[4] = this.txtSm1.Text.Trim();
            DataRow[5] = this.txtSm2.Text.Trim();
            DataRow[6] = string.Format("{0}", jeHs);
            DataRow[7] = string.Format("{0}", jeFs);
            this.dataGridView1.Rows.Add(DataRow);

            decimal sumJe = jeHs;
            decimal noSumJe = jeFs;
            if (!string.IsNullOrEmpty(this.txtSumJe.Text.Trim()))
                sumJe += decimal.Parse(this.txtSumJe.Text.Trim());
            if (!string.IsNullOrEmpty(this.txtNoSumJe.Text.Trim()))
                noSumJe += decimal.Parse(this.txtNoSumJe.Text.Trim());
            this.txtSumJe.Text = string.Format("{0}", sumJe);
            this.txtNoSumJe.Text = string.Format("{0}", noSumJe);

            rowCount = this.dataGridView2.RowCount;
            String[] goodDataRow = new String[10];
            DataTable dt = sacfBLL.GetAll(no);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                goodDataRow[0] =(rowCount + 1).ToString();
                goodDataRow[1] =dt.Rows[i]["no"].ToString();
                goodDataRow[2] = dt.Rows[i]["nono"].ToString();
                goodDataRow[3] =dt.Rows[i]["id"].ToString();
                goodDataRow[4] = dt.Rows[i]["goods"].ToString();
                goodDataRow[5] = dt.Rows[i]["unit"].ToString();
                goodDataRow[6] =dt.Rows[i]["sl"].ToString();
                goodDataRow[7] = dt.Rows[i]["price_fs"].ToString();
                goodDataRow[8] = dt.Rows[i]["je_fs"].ToString();
                goodDataRow[9] = dt.Rows[i]["tax"].ToString();
                this.dataGridView2.Rows.Add(goodDataRow);
            }

            this.txtNo.Clear();
            this.txtSm1.Clear();
            this.textBox1.Clear();
            this.txtSm2.Clear();
            this.txtKd.Clear();
            this.txtTh.Clear();
            this.txtKp.Clear();
            this.txtSk.Clear();

            this.txtNo.Focus();
        }

        private void txtInvoiceCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.chkF.Focus();
            }
        }

        private void txtZw_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtBei.Focus();
            }
        }

        private void txtBei_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.btnAddRecord.Focus();
            }
        }

        private void btnQuit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string goods="无金额调整";
            decimal cas=0;
            string f7 = "0";
            decimal hj = decimal.Parse(this.txtSumJe.Text.Trim());
            decimal nhj = decimal.Parse(this.txtNoSumJe.Text.Trim());
            if (!string.IsNullOrEmpty(this.textBox17.Text.Trim()) && !"0".Equals(this.textBox17.Text.Trim()))
            {
                if (!"17".Equals(this.textBox16.Text.Trim()) && !"13".Equals(this.textBox16.Text.Trim()))
                {
                    MessageBox.Show("有金额调整,税率应为17或13！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.textBox16.Focus();
                    return;
                }
                hj += decimal.Parse(this.textBox17.Text.Trim());
                if (hj <= 0)
                {
                    MessageBox.Show(string.Format("有金额调整，整张发票合计金额为：{0}\n小于零，不可操作！", hj), "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.textBox16.Focus();
                    return;
                }
                if (MessageBox.Show(string.Format("有金额调整，整张发票合计金额为：{0}\n请检查各项目是否正确，是否保存[Y/N]？", hj), "提问窗", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    return;
                goods = string.Format("*{0}税{1} {2}", this.textBox17.Text.Trim(), this.textBox16.Text.Trim(), this.textBox15.Text.Trim());
                cas = decimal.Parse(this.textBox17.Text.Trim());
                f7 = "1";
                nhj += decimal.Parse(this.textBox17.Text.Trim()) * 100 / (100 + decimal.Parse(this.textBox16.Text.Trim()));
            }
            else
            {
                if (MessageBox.Show("无金额调整，\n请检查各项目是否正确，是否保存[Y/N]？", "提问窗", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    return;
            }
            MisEntity.Invoice invoice = new MisEntity.Invoice();
            invoice.je_hs = hj;
            invoice.je_fs = nhj;
            invoice.OPER = accountUser.UserCode;
            invoice.bei = this.txtInvoiceNum.Text.Trim();
            invoice.goods = goods;
            invoice.je_cas = cas;
            invoice.DM = this.txtCusCode.Text.Trim();
            invoice.ID = this.txtCusDepCode.Text.Trim();
            if (this.dataGridView2.Rows.Count > 0)
            {
                IList<MisEntity.Sacf> list = new List<MisEntity.Sacf>(this.dataGridView1.Rows.Count);
                MisEntity.Sacf entity = null;
                DataGridViewRow dr = null;
                for (int i = 0; i < this.dataGridView2.Rows.Count; i++)
                {
                    dr = this.dataGridView2.Rows[i];
                    entity = new MisEntity.Sacf();
                    entity.NO = dr.Cells["data1"].Value.ToString();
                    entity.NONO = decimal.Parse(dr.Cells["data2"].Value.ToString());
                    entity.ID = dr.Cells["data3"].Value.ToString();
                    entity.OP_KP = accountUser.UserCode;
                    entity.NO_CUS = this.txtInvoiceNum.Text.Trim();
                    entity.F7 =char.Parse(f7);
                    list.Add(entity);
                }
                string invoiceNo = sacfBLL.Billing(invoice, list);
                this.btnSave.Enabled = false;
                this.btnCan.Enabled = false;
                MessageBox.Show(string.Format("单据已存盘，编号：{0}，总金额：{1}。是否打印清单[y/n]？", invoiceNo, hj), "提问窗", MessageBoxButtons.OK, MessageBoxIcon.Question);

                this.txtNo.Enabled = false;
                this.txtBei.Enabled = false;
                this.textBox15.Enabled = false;
                this.textBox16.Enabled = false;
                this.textBox17.Enabled = false;

                this.btnAdd.Enabled = true;
                this.btnAddRecord.Enabled = false;
                this.btnDelRecord.Enabled = false;
                this.btnPrint.Enabled = true;
                this.btnQuit.Enabled = true;
            } 
        }

        private void textBox15_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.textBox16.Focus();
            }
        }

        private void textBox16_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.textBox17.Focus();
            }
        }

        private void textBox17_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.btnAddRecord.Focus();
            }
        }

        private void toolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("calc.exe");
        }

        private void btnCan_Click(object sender, EventArgs e)
        {
            this.openStarDate.Enabled = false;
            this.openEndDate.Enabled = false;
            this.txtCusCode.Enabled = false;
            this.txtInvoiceNum.Enabled = false;
            this.txtCusDepCode.Enabled = false;
            this.txtInvoiceCode.Enabled = false;
            this.chkF.Enabled = false;

            this.txtNo.Enabled = false;
            this.txtBei.Enabled = false;
            this.textBox15.Enabled = false;
            this.textBox16.Enabled = false;
            this.textBox17.Enabled = false;

            this.btnSave.Enabled = false;
            this.btnCan.Enabled = false;
            this.btnAdd.Enabled = true;
            this.btnAddRecord.Enabled = false;
            this.btnDelRecord.Enabled = false;
            this.btnPrint.Enabled = true;
            this.btnQuit.Enabled = true;
        }

        private void btnDelRecord_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.CurrentRow != null)
            {
                string no=this.dataGridView1.CurrentRow.Cells["invoice"].Value.ToString();
                this.dataGridView1.Rows.Remove(this.dataGridView1.CurrentRow);
                DataGridViewRow dr = null;
                for (int i = 0; i < this.dataGridView2.Rows.Count; i++)
                {
                    dr = this.dataGridView2.Rows[i];
                    if (no.Equals(dr.Cells["data1"].Value.ToString()))
                        this.dataGridView2.Rows.Remove(dr);

                }
            }
        }

        private void btnRef_Click(object sender, EventArgs e)
        {
            Point mousePoint = MousePosition;
            Point point = this.PointToClient(mousePoint);
            this.contextMenuStrip1.Show(this, point);
        }

        private void openStarDate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.openEndDate.Focus();
            }
            
        }

        private void openEndDate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtCusCode.Focus();
            }
        }
    }
}
